package com.ideasindustry.photoontaje.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.IOException;

public class ImageUtils {

	/**
	 * Retrieves all the pixels from an image in a multi-dimensional array
	 * 
	 * @param image
	 * @return a multidimensional array with pixels
	 * @throws IOException
	 */
	public static int[][] getPixels(Image image) throws IOException {
		int w = image.getWidth(null);
		int h = image.getHeight(null);
		int pix[] = new int[w * h];
		PixelGrabber grabber = new PixelGrabber(image, 0, 0, w, h, pix, 0, w);

		try {
			if (grabber.grabPixels() != true) {
				throw new IOException("Grabber returned false: "
						+ grabber.status());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		int pixels[][] = new int[w][h];
		for (int x = w; x-- > 0;) {
			for (int y = h; y-- > 0;) {
				pixels[x][y] = pix[y * w + x];
			}
		}

		return pixels;
	}

	
	/**
	 * Scales an image maintaining the aspect ration
	 * 
	 * @param image
	 * @param thumbWidth
	 * @param thumbHeight
	 * @return the scaled image
	 */
	public static Image scaleImage(Image image, int thumbWidth, int thumbHeight){

		// Make sure the aspect ratio is maintained, so the image is not skewed
		double thumbRatio = (double) thumbWidth / (double) thumbHeight;
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		double imageRatio = (double) imageWidth / (double) imageHeight;
		if (thumbRatio < imageRatio) {
			thumbHeight = (int) (thumbWidth / imageRatio);
		} else {
			thumbWidth = (int) (thumbHeight * imageRatio);
		}

		// Draw the scaled image
		BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight,BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2D = thumbImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

		return thumbImage;
	}
	
	

}
